package com.imachen.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.imachen.domain.*;
import com.imachen.dto.StockDto;
import com.imachen.enums.GlobalExceptionCode;
import com.imachen.exception.GlobalCustomException;
import com.imachen.feign.ProductService;
import com.imachen.feign.PurchaseService;
import com.imachen.mapper.StockMapper;
import com.imachen.properties.StockThresholdProperties;
import com.imachen.result.JSONResult;
import com.imachen.service.IStockLogService;
import com.imachen.service.IStockService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.imachen.service.IStockWarningLogService;
import com.imachen.util.AssertUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author imachen
 * @since 2022-09-29
 */
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements IStockService {

    @Autowired
    private ProductService productService;

    @Autowired
    private StockThresholdProperties stockThresholdProperties;

    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    private IStockWarningLogService stockWarningLogService;

    @Autowired
    private IStockLogService stockLogService;

    // 出入库
    @Override
    public void inOutBound(StockDto stockDto) {
       Stock stock = selectStock(stockDto.getProductId());
       if (stockDto.getStatus() == 0){ //入库
           if (stock == null){ // 如果stock不存在 则新建库存信息
               saveStock(stockDto);
           }else {
               // 存在就修改添加库存
               stock.setCount(stock.getCount() + stockDto.getCount());
               updateById(stock);
               // 添加入库成功日志
               saveStockLog(stockDto, stock);
               // 修该采购申请的状态为采购完成2
               JSONResult jsonResult = purchaseService.get(stock.getProductId());
               String pur = JSONObject.toJSONString(jsonResult.getData());
               PurchaseApply purchaseApply = JSON.parseObject(pur, PurchaseApply.class);
               purchaseService.approval(purchaseApply.getId(),2);

           }
       }else if(stockDto.getStatus() == 1){
           //出库
           Integer count = stock.getCount();
           if (count < stockDto.getCount()){// 库存不足
               // 判断库存数量是否小于警告阈值
               if (count < stockThresholdProperties.getThreshold()){
                   // 添加库存警告日志
                   saveStockWarningLog(stock);
                   // 提交采购申请单
                   savePurchase(stock);
               }
           }else { // 库存充足
               // 修改删除库存
               stock.setCount(stock.getCount() - stockDto.getCount());
               updateById(stock);
           }

       }
    }

    // 添加库存表
    private void saveStock(StockDto stockDto) {
        Stock stock;
        stock = new Stock();
        stock.setCount(stockDto.getCount());
        stock.setProductId(stockDto.getProductId());
        JSONResult jsonResult = productService.get(stockDto.getProductId());
        AssertUtil.isTrue(jsonResult.isSuccess(), GlobalExceptionCode.ERROR);
        Object data = jsonResult.getData();
        AssertUtil.isNotNull(data, GlobalExceptionCode.ERROR);
        String jsonStr = JSONObject.toJSONString(data);
        Product product = JSON.parseObject(jsonStr, Product.class);
        stock.setProductName(product.getProductName());
        stock.setCreateTime(new Date());
        insert(stock);
    }

    // 添加库存警告日志
    private void saveStockWarningLog(Stock stock) {
        Date date = new Date();
        StockWarningLog stockWarningLog = new StockWarningLog();
        BeanUtils.copyProperties(stock, stockWarningLog);
        stockWarningLog.setInfo(stock.getProductName() + "库存不足了，请及时采购！");
        stockWarningLog.setCreateTime(date);
        stockWarningLogService.insert(stockWarningLog);
    }

    // 添加库存日志
    private void saveStockLog(StockDto stockDto, Stock stock) {
        Date date = new Date();
        StockLog stockLog = new StockLog();
        BeanUtils.copyProperties(stock, stockLog);
        stockLog.setCount(stockDto.getCount());
        stockLog.setCreateTime(date);
        stockLog.setStatus(stockDto.getStatus());
        stockLogService.insert(stockLog);
    }

    // 提交采购申请
    private void savePurchase(Stock stock) {
        PurchaseApply purchaseApply = new PurchaseApply();
        purchaseApply.setProductId(stock.getProductId());
        purchaseApply.setProductName(stock.getProductName());
        purchaseApply.setCreateTime(new Date());
        purchaseApply.setCount(100);
        purchaseApply.setStatus(0);
        purchaseService.saveOrUpdate(purchaseApply);
        throw new GlobalCustomException(GlobalExceptionCode.STOCK_ERROR);
    }

    // 查询库存信息
    private Stock selectStock(Long productId) {
        Wrapper<Stock> wrapper = new EntityWrapper<>();
        wrapper.eq("product_id", productId);
        return selectOne(wrapper);
    }

    // 查询缺货库存信息
    @Override
    public List<Stock> lack() {
        // 获取库存阈值
        Integer threshold = stockThresholdProperties.getThreshold();
        Wrapper<Stock> wrapper = new EntityWrapper<>();
        wrapper.lt("count", threshold);
        List<Stock> stocks = selectList(wrapper);
        return stocks;
    }


}
